/* 
Copyright (c) 2011, Sulaiman Mustafa and Mohammed Mustafa
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sqlite3.h>
#include <errno.h>
#include "stag.h"
#include "gl.h"
#include "db.h"

#define STAG_ERROR_MESSAGE_MISSING_ARGS \
"Error: missing arguments. see -oh for more information.\n"

#define STAG_MISSING_ARGS \
{fprintf(stderr, STAG_ERROR_MESSAGE_MISSING_ARGS);	exit(1);}

struct stringlist files;
struct stringlist tags;





void args_parser_stage1(int argc, char **argv){
	char* current;
	char* previous;
	int i, tagf=0;
	for (i=1; i<argc; ++i){
		previous=argv[i-1];
		current=argv[i];
		
		if(!strcmp("--", current)){
			tagf=1;
		}
		else if (!strcmp("-custom-base", current)){
			continue;
		}
		else if (!strcmp("-custom-base", previous)){
			STAG_SET_OPTION(STAG_OPTION_CUSTOM_BASE);
			stagBaseDir=current;
		}
		else if (!strcmp("-initialize", current)){
			STAG_SET_OPTION(STAG_OPTION_INITIALIZE);
		}
		else if (!strcmp("-locate-database", current)){
			STAG_SET_OPTION(STAG_OPTION_LOCATE_DB);
		}
		else if (!strcmp("-print-tags", current)){
			STAG_SET_OPTION(STAG_OPTION_PRINT_TAGS);
		}
		else if (!strcmp("-set-default", current)){
			STAG_SET_OPTION(STAG_OPTION_DEFAULT_BASE);
		}
		else if (!strcmp("-recurse", current)){
			STAG_SET_OPTION(STAG_OPTION_RECURSE);
		}
		else if (!strcmp("-follow-links", current)){
			STAG_SET_OPTION(STAG_OPTION_FOLLOW_SYMBOLIC_LINKS);
		}
		else if (!strcmp("-help", current)){
			STAG_SET_OPTION(STAG_OPTION_HELP);
		}
		else if (!strcmp("-version", current)){
			STAG_SET_OPTION(STAG_OPTION_VERSION);
		}
		else if (!strcmp("-add", current)){ /*|| !strcmp("-أضف", current, 7)*/
			stagOperation=STAG_OP_ADD;
		}
		else if (!strcmp("-remove", current)){
			stagOperation=STAG_OP_REMOVE;
		}
		else if (!strcmp("-purge", current)){
			stagOperation=STAG_OP_REMOVE;
		}
		else if (!strcmp("-find", current)){
			stagOperation=STAG_OP_FIND;
		}
		else{
			if (tagf) add_string_to_stringlist(&tags, current);
			else add_string_to_stringlist(&files, current);
		}
	}
	stagTagCount=tags.count;
	stagTagList=tags.list;		
}

void args_parser_stage2(){
	FILE *fd;
	char *syswide;
	/* core options */
	if(!STAG_IS_OPTION(STAG_OPTION_CUSTOM_BASE))
		stag_gl_locate_base_dir();

	stag_gl_init(); /*Must be here to set up stagBaseDir*/
	
	if (STAG_IS_OPTION(STAG_OPTION_DEFAULT_BASE)){
		syswide=initialize_string(getenv(HOME));
		syswide=append_string(syswide,  STAG_DIR_SEP STAG_CONFIG_DIR STAG_DATABASE_LOCATION_FILE);
		if(!(fd=fopen(syswide, "w"))){
			fprintf(stderr, "Could not access '%s':%s\n", syswide, strerror(errno));
			exit(1);
		}
		if(!fprintf(fd, "%s", stagBaseDir)){
			fprintf(stderr, "Could not write to '%s':%s\n", syswide, strerror(errno));
			exit(1);
		}
		fclose(fd);
		fprintf(stderr, "sucessfully set '%s' as default system database.\n", stagBaseDir);
		exit(0);
	}
	
	
	
	/* run and quit options */
	if (STAG_IS_OPTION(STAG_OPTION_HELP)){
		fprintf(stdout, STAG_HELP_MESSAGE);
		exit(0);
	}
	if (STAG_IS_OPTION(STAG_OPTION_VERSION)){
		fprintf(stdout, 	STAG_NAME " " STAG_VERSION "\n\n"
								STAG_COPYRIGHTS
								STAG_NAME " is a part of the Sigh.asia Tagger Project.\n");
		exit(0);
	}
	if(STAG_IS_OPTION(STAG_OPTION_INITIALIZE)){
			sqlite3_close(stag_db_sql_open());
			fprintf(stdout, "Initialized database in '%s'.\n", stagBaseDir);
			exit(0);
	}
	if(STAG_IS_OPTION(STAG_OPTION_LOCATE_DB)){
			printf("%s\n", stagBaseDir);
			exit(0);
	}

	/* operation check */
	if (!stagOperation){
		fprintf(stderr, "Error: an operation must be specified. see -help\n");
		exit(1);
	}
	
}


int main(int argc, char **argv){
	int i;
	struct stringlist *out=NULL;
	
	/* local variable initialization & checks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
	initialize_stringlist(&files);
	initialize_stringlist(&tags);
	
	/* argument parser ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
	args_parser_stage1(argc, argv);
	args_parser_stage2();

	
	/* logic start ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
	stag_db_init();
	/*printf( 	"%d\n" "%d\n" "%d\n" "%d\n" "%d\n" "%d\n" "%d\n" "%d\n" "%d\n" "%d\n" "%d\n" "%d\n" "%d\n",
				STAG_IS_OPTION( STAG_OPTION_RECURSE ),
				STAG_IS_OPTION( STAG_OPTION_INITIALIZE ),
				STAG_IS_OPTION( STAG_OPTION_CUSTOM_BASE ),
				STAG_IS_OPTION( STAG_OPTION_FOLLOW_SYMBOLIC_LINKS ),
				STAG_IS_OPTION( STAG_OPTION_DEFAULT_BASE ),
				STAG_IS_OPTION( STAG_OPTION_LOCATE_DB ),
				STAG_IS_OPTION( STAG_OPTION_PRINT_TAGS ),
				STAG_IS_OPTION( STAG_OPTION_HELP ),
				STAG_IS_OPTION( STAG_OPTION_VERSION ),
				STAG_IS_OPERATION(STAG_OP_ADD),
				STAG_IS_OPERATION(STAG_OP_FIND),
				STAG_IS_OPERATION(STAG_OP_PURGE),
				STAG_IS_OPERATION(STAG_OP_REMOVE));	*/
	
	if(STAG_IS_OPERATION(STAG_OP_REMOVE)||STAG_IS_OPERATION(STAG_OP_ADD)) 
		if(!files.count) stag_db_mod(NULL); 
		else for (i=0;i<files.count;++i) stag_gl_mod(*(files.list+i), STAG_IS_OPTION(STAG_OPTION_RECURSE), STAG_IS_OPTION(STAG_OPTION_FOLLOW_SYMBOLIC_LINKS));
	else if(STAG_IS_OPERATION(STAG_OP_FIND)) 
		if(!files.count) out=stag_db_find(NULL); 
		else out=stag_db_find(*files.list);
	else if(STAG_IS_OPERATION(STAG_OP_PURGE)) stag_gl_purge();
	
	if(out) for (i = 0; i<out[0].count; ++i) printf("%s\t%s\n", *(out[0].list+i), (STAG_IS_OPTION(STAG_OPTION_PRINT_TAGS)?(*(out[1].list+i)):""));
	return 0;
}

